// ProductService.java
package com.example.developer.service;

import com.example.developer.model.Product;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;

@Service
public class ProductService {
    private final List<Product> products = new ArrayList<>();
    private final AtomicLong idCounter = new AtomicLong(1);

    public ProductService() {
        // 初始化一些假数据
        initializeSampleData();
    }

    private void initializeSampleData() {
        products.add(new Product(idCounter.getAndIncrement(), "iPhone 14", 5999.00, 50, "最新款苹果手机"));
        products.add(new Product(idCounter.getAndIncrement(), "MacBook Pro", 12999.00, 30, "苹果笔记本电脑"));
        products.add(new Product(idCounter.getAndIncrement(), "AirPods Pro", 1899.00, 100, "无线蓝牙耳机"));
        products.add(new Product(idCounter.getAndIncrement(), "iPad Air", 4399.00, 40, "平板电脑"));
    }

    // 获取所有商品
    public List<Product> getAllProducts() {
        return new ArrayList<>(products);
    }

    // 根据ID获取商品
    public Product getProductById(Long id) {
        return products.stream()
                .filter(product -> product.getId().equals(id))
                .findFirst()
                .orElse(null);
    }

    // 添加商品
    public Product addProduct(Product product) {
        product.setId(idCounter.getAndIncrement());
        products.add(product);
        return product;
    }

    // 更新商品
    public Product updateProduct(Long id, Product product) {
        for (int i = 0; i < products.size(); i++) {
            if (products.get(i).getId().equals(id)) {
                product.setId(id);
                products.set(i, product);
                return product;
            }
        }
        return null;
    }

    // 删除商品
    public boolean deleteProduct(Long id) {
        return products.removeIf(product -> product.getId().equals(id));
    }
}